import {
  ExpertAppointmentTimes,
  ExpertDetail,
  ExpertEvaluate,
  ExpertVideos,
} from '@/api/expert';
import { GetUserInfo } from '@/api/user';
import useUserExamine from '@/hooks/useUserExamine';
import { Button, Icon, Tab, Tabs } from '@antmjs/vantui';
import { OrderDetail } from '@/api/order';
import {
  Image,
  Navigator,
  RichText,
  Text,
  Video,
  View,
} from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import classNames from 'classnames';
import { useMemo, useState } from 'react';
import { useRequest } from 'taro-hooks';
import { TemplateMessage } from 'types/user';
import { useAdjustingPricing } from '../expert/appointment/components/useAdjustingPricing';
import CutDown from './components/CutDown';
import Tags from './components/Tags';
import Tip from './components/Tip';
import useReservationComfirm from './components/useReservationComfirm';
import useReservationDetail from './components/useReservationDetail';
import useReservationSuccess from './components/useReservationSuccess';
import useCustomerService from '@/components/useCustomerService';
import Empty from '@/components/Empty';

if (process.env.TARO_ENV !== 'h5') {
  require('@tarojs/taro/html.css');
}

export default function Page() {
  const router = useRouter();

  const readonly = useMemo(() => router?.params?.readonly === 'true', [router]);

  const [tabName, setTabName] = useState<'default' | 'videos'>('default');
  const [videoUrl, setVideoUrl] = useState<string | undefined>(undefined);

  const { renderNode: renderServiceNode, open: openService } =
    useCustomerService();

  const { data: detail, refresh } = useRequest(() =>
    ExpertDetail({ expertId: router?.params?.id! })
  );

  // ?获取评价数量
  const { data: comments } = useRequest(
    () => ExpertEvaluate({ expertId: detail?.id + '' }),
    {
      ready: !!detail?.id,
    }
  );

  const { isUserExamine } = useUserExamine();

  const { data: user } = useRequest(GetUserInfo);

  //是否是专家本人访问
  const isSelf = useMemo(() => user?.id === detail?.user_id, [user, detail]);

  //获取专家相关资料
  const { data: videos } = useRequest(() =>
    ExpertVideos({ expertId: router.params?.id! })
  );

  //获取订单详情
  const { data: order } = useRequest(
    () => OrderDetail({ id: detail?.partin_id! }),
    {
      ready: Boolean(detail?.partin_id),
    }
  );

  //确认预约
  const { renderNode: renderConfirmNode, open: openConfirm } =
    useReservationComfirm({
      detail: detail!,
      onSuccess: function () {
        refresh();
      },
    });

  //预约成功
  const { renderNode: renderSuccessNode, open: openSuccess } =
    useReservationSuccess({
      address: order?.time?.address as string,
      time: order?.time?.appoint_time as string,
      code: order?.code as string,
      onClose: function () {
        refresh();
      },
    });

  //查看预约
  const { renderNode: renderDetailNode, open: openDetail } =
    useReservationDetail({
      detail: detail!,
      onFinish: function () {
        refresh(); //倒计时结束刷新
      },
    });

  //查询可预约时间
  const { data: time } = useRequest(
    () => ExpertAppointmentTimes({ expertId: detail?.id! }),
    {
      ready: Boolean(detail?.id),
    }
  );

  //调整定价， 仅专家可见
  const { renderNode: renderADNode, open: openAd } = useAdjustingPricing({
    onSuccess: function () {
      refresh();
    },
  });

  return (
    <>
      {isSelf && <Tip />}
      <View
        style={{
          paddingBottom: `calc(80px + env(safe-area-inset-bottom))`,
        }}
      >
        {tabName === 'default' && (
          <View
            className='bg-cover bg-top pt-8 pb-4'
            style={{
              backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/bg5.jpg)`,
            }}
          >
            {/* logo */}
            <Image
              src='https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/logo-light.svg'
              mode='aspectFill'
              className='w-[252px] h-[72px] ml-[90px] mb-[60px] drop-shadow-md shadow-black'
            />
            {/* info */}
            <View className=' bg-white rounded-lg p-4 relative mx-auto w-[710px]'>
              {/* avatar */}
              {detail?.headimg && (
                <View className=' absolute right-5 -top-[160px] flex flex-col'>
                  <Image
                    src={detail.headimg}
                    mode='aspectFill'
                    className='w-[220px] h-[220px] bg-slate-300  shadow-lg rounded-full border-6 border-solid border-white'
                  />

                  {Boolean(comments?.length) && (
                    <Navigator
                      hoverClass='none'
                      url={`/pages/professional/comments?id=${detail?.id}`}
                      className=' bg-gradient-to-r from-[#AAD0ED] to-[#1581CB] relative -top-[40px] left-1/2 -translate-x-1/2 rounded-full text-xs text-center text-white py-1 inline-flex items-center pl-2'
                    >
                      <View
                        className=' w-4 h-4 mr-1 bg-cover'
                        style={{
                          backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-zan.svg)`,
                        }}
                      ></View>
                      专家评价 （{comments?.length}）
                    </Navigator>
                  )}
                </View>
              )}

              <Text className=' block text-black text-[36px] font-bold'>
                {detail?.name}
              </Text>
              <View className='my-2'>
                <Tags list={detail?.tags?.split(',')!} />
              </View>
              <Text className=' block'>{detail?.company}</Text>

              {detail?.goodat && (
                <View className='flex mt-2'>
                  <View
                    className='w-[103px] h-[22px] mr-2 bg-cover mt-[4px]'
                    style={{
                      backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-ly.png)`,
                    }}
                  ></View>
                  <View className='flex-1 text-xs text-gary3'>
                    {detail?.goodat}
                  </View>
                </View>
              )}
            </View>

            {/* banner */}
            <Image
              src='https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/banner1.png'
              mode='aspectFill'
              className=' mt-3 w-[710px] h-[180px] block mx-auto'
            />
          </View>
        )}

        {tabName === 'videos' && videoUrl && (
          <Video
            src={videoUrl}
            className='h-[440px] w-full block'
            autoplay
            controls
          />
        )}

        <View className={classNames('bg-white')}>
          <Tabs
            onChange={(e) => {
              setTabName(e.detail.name as 'default' | 'videos');
            }}
          >
            <Tab title='专家介绍' name='default'>
              <View className=' p-4 bg-white text-sm taro_html'>
                <RichText nodes={detail?.info} />
              </View>
            </Tab>
            <Tab title='相关资料' name='videos'>
              <View className='p-4 bg-white'>
                <View className=' py-12'>
                  <Empty
                    title='暂无资料'
                    icon={
                      <Image
                        src='https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/empty-1.png'
                        className=' w-[381px] h-[311px] block -mb-[50px]'
                      />
                    }
                  />
                </View>
                {videos?.map((item) => (
                  <View
                    className='flex items-center mt-4'
                    key={item.id}
                    onClick={async () => {
                      if (item.url)
                        return Taro.navigateTo({
                          url: `/pages/webview?url=${encodeURIComponent(
                            item.url
                          )}`,
                        });

                      if (item.video?.includes('.pdf')) {
                        const { tempFilePath } = await Taro.downloadFile({
                          url: item.video,
                        });

                        Taro.openDocument({ filePath: tempFilePath });
                        return;
                      }
                      setVideoUrl(item.video);
                    }}
                  >
                    <View
                      className={classNames(
                        'w-[20px] h-[20px] rounded-full bg-white border-[6px] border-gary3 mr-2',
                        {
                          'border-primary': videoUrl === item.video,
                        }
                      )}
                    />
                    <View className='text-xs p-3 text-black flex items-center bg-[#F6F7FB] rounded-lg flex-1'>
                      <View
                        className='w-4 h-4 mr-1 bg-cover'
                        style={{
                          backgroundImage: `url(${
                            item.url
                              ? 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-wechat.svg'
                              : item.video?.includes('.pdf')
                              ? 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-pdf.svg'
                              : 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-video.svg'
                          })`,
                        }}
                      />
                      <Text>{item?.title}</Text>

                      {(item.video?.includes('.pdf') || item.url) && (
                        <View className=' text-xs text-primary flex items-center ml-auto'>
                          <Icon name='search' className=' text-inherit mr-1' />
                          查看
                        </View>
                      )}

                      {videoUrl === item.video && (
                        <View className='ml-auto flex items-center text-success'>
                          <View
                            className='w-[32px] h-[32px] bg-cover mr-1'
                            style={{
                              backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-playing.svg)`,
                            }}
                          />
                          播放中
                        </View>
                      )}
                    </View>
                  </View>
                ))}
              </View>
            </Tab>
          </Tabs>
        </View>

        {/* footer */}
        {!readonly && (
          <View
            className=' fixed left-0 right-0 bottom-0 bg-white pt-2 px-4 shadow-footer'
            style={{
              paddingBottom: `calc(10px + env(safe-area-inset-bottom))`,
            }}
          >
            {!user?.id && (
              <Button
                className=' opacity-0 left-0 top-0 absolute w-full h-full z-10'
                onClick={() => {
                  Taro.redirectTo({ url: `/pages/login/index` });
                }}
              />
            )}

            {(isSelf && (
              <>
                <Button disabled block className=' text-white'>
                  咨询价格：
                  <Text className=' font-bold text-lg'>
                    {detail?.beans}
                  </Text>{' '}
                  帮豆
                </Button>
                <View className=' text-xs text-center text-gary4 mt-2'>
                  <Text
                    className=' font-bold text-primary'
                    onClick={() => openAd()}
                  >
                    调整定价
                  </Text>
                </View>
              </>
            )) || (
              <>
                {(detail?.partin && (
                  <>
                    {(detail?.partin_status === 1 && (
                      <Button
                        size='large'
                        type='primary'
                        block
                        onClick={() => openSuccess()}
                      >
                        <View
                          className='w-[120px] h-[120px] bg-cover absolute left-[30px] -top-[30px]'
                          style={{
                            backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-success2.png)`,
                          }}
                        ></View>
                        预约成功，可点击查看详情
                      </Button>
                    )) || (
                      <>
                        <View className=' right-2 -top-[100px] absolute z-10'>
                          <CutDown
                            value={detail?.partin_time}
                            onFinish={() => {
                              refresh();
                            }}
                          />
                        </View>
                        <Button
                          size='large'
                          type='primary'
                          block
                          onClick={() => openDetail()}
                        >
                          预约待确认，可点击查看详情
                        </Button>
                      </>
                    )}
                  </>
                )) || (
                  <>
                    {((user?.beans || 0) >= (detail?.beans || 0) && (
                      <>
                        {(time?.length && (
                          <>
                            <Button
                              size='large'
                              type='primary'
                              block
                              onClick={async () => {
                                await isUserExamine();

                                //@ts-ignore
                                await Taro.requestSubscribeMessage({
                                  tmplIds: [
                                    TemplateMessage.预约结果通知,
                                    TemplateMessage.活动开始提醒,
                                  ],
                                });
                                openConfirm();
                              }}
                            >
                              <View
                                className='w-[206px] h-[48px] bg-cover absolute -right-1 -top-[30px] text-xs text-white flex items-center justify-center'
                                style={{
                                  backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-buy1.svg)`,
                                }}
                              >
                                <Text className=' text-lg font-bold block mr-1 leading-none'>
                                  {detail?.beans}
                                </Text>
                                帮豆
                              </View>
                              立即预约
                            </Button>
                            <View className=' text-center text-xs mt-1 text-gary4'>
                              完成咨询评价后， 您将获得
                              <Text className=' text-primary font-bold'>
                                {detail?.points || 0}
                              </Text>
                              积分
                            </View>
                          </>
                        )) || (
                          <Button
                            size='large'
                            type='primary'
                            block
                            onClick={() => openService()}
                          >
                            具体时间请联系臻会帮客服
                          </Button>
                        )}
                      </>
                    )) || (
                      <>
                        <Button size='large' type='primary' block disabled>
                          {detail?.beans}帮豆 预约咨询
                        </Button>
                        <View className=' text-xs text-gary4 text-center mt-2'>
                          帮豆不足（帮豆余额{user?.beans}）
                          <Text
                            className=' text-primary font-bold'
                            onClick={async () => {
                              await isUserExamine();
                              Taro.navigateTo({
                                url: `/pages/my/bangdou/index?from=detail`,
                              });
                            }}
                          >
                            开通会员
                          </Text>
                        </View>
                      </>
                    )}
                  </>
                )}
              </>
            )}
          </View>
        )}
      </View>

      {renderConfirmNode()}
      {renderSuccessNode()}
      {renderDetailNode()}
      {renderADNode()}
      {renderServiceNode()}
    </>
  );
}
